<template>
  <el-card shadow="never" class="border-0">

    <!-- 搜索 -->
    <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label="模板名称">
            <el-select v-model="searchForm.templateId" filterable placeholder="模板名称">
              <el-option v-for="item in templateDic" :key="item.templateId" :label="item.templateName"
                :value="item.templateId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="5" :offset="0">
            <el-form-item label="申请人">
              <el-input v-model="searchForm.applicantName" placeholder="申请人" clearable></el-input>
            </el-form-item>
          </el-col> -->
        <!-- <el-col :span="5">
            <el-form-item label="审批状态">
              <el-select v-model="searchForm.status" filterable placeholder="请选择审批状态">
                <el-option label="待审批" value=0></el-option>
                <el-option label="审批通过" value=1></el-option>
                <el-option label="审批拒绝" value=2></el-option>
                <el-option label="审批中" value=3></el-option>
                <el-option label="取消申请" value=4></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        <el-col :span="5">
          <div class="flex items-center justify-end">
            <el-button type="primary" @click="initTableData(1)">搜索</el-button>
            <el-button @click="resetSearchForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格数据 -->
    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column label="模版名称" align="center">
        <template #default="{ row }">
          {{ row.templateName }}
        </template>
      </el-table-column>

      <el-table-column label="申请人" align="center">
        <template #default="{ row }">
          {{ row.applicantName }}
        </template>
      </el-table-column>

      <!-- <el-table-column label="申请描述" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.description }}
          </template>
        </el-table-column> -->

      <el-table-column label="审批结果" align="center">
        <template #default="{ row }">
          {{ formatRecordResult(row.approvalResult) }}
        </template>
      </el-table-column>

      <!-- <el-table-column label="审批状态" align="center">
          <template #default="{ row }">
            {{ formatRequestStatus(row.status) }}
          </template>
        </el-table-column> -->

      <el-table-column label="申请时间" align="center">
        <template #default="{ row }">
          {{ dateFormatter(row.approvalTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" text @click="handleShow(scope.row)">查看详情</el-button>
          <el-button type="primary" size="small" text v-if="scope.row.approvalType == 1"
            @click="certPreview(scope.row)">预览</el-button>
          <el-button type="primary" size="small" text @click="showApprovalDialog(scope.row)">审批</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
        @current-change="initTableData" />
    </div>
  </el-card>

  <!-- 查看详情弹窗 -->
  <!-- <el-dialog v-model="approvalDetailDialogVisible" title="详情信息" width="40%" height="50%" align-center>
    <el-form :model="approvalDetail" label-width="120px" :inline="false">
      <el-form-item label="申请人：">
        <span>{{ approvalDetail.approvalRequestDto.applicantName }}</span>
      </el-form-item>
      <el-form-item label="模板名称：">
        <span>{{ approvalDetail.approvalTemplateDto.templateName }}</span>
      </el-form-item>
      <el-form-item label="申请描述：">
        <span>{{ approvalDetail.approvalRequestDto.description }}</span>
      </el-form-item>
      <el-form-item label="审批状态：">
        <span>{{ formatRequestStatus(approvalDetail.approvalRequestDto.status) }}</span>
      </el-form-item>

      <el-steps :align-center="true">
        <el-tooltip class="item" effect="dark" placement="top-start" v-for="(item, key) in steps" :key="key"
          :content="item.tooltipInfo">
          <el-step :title="item.title" :status="item.status">
            <template #description>
              <div v-if="item.approvalType == 1">
                <span>{{ item.description }}</span>
              </div>
              <div v-if="item.approvalType == 2" v-for="(desc, key) in item.description" :key="desc.key"
                style="font-size: 13px;">
                <span>{{ desc.name }}</span><span>({{ desc.result }})</span><br><span>{{ desc.time }}</span>
              </div>
            </template>
          </el-step>
        </el-tooltip>
      </el-steps>

      <el-form-item v-if="approvalDetail.approvalRequestDto.remark" label="拒绝原因：">
        <span>{{ approvalDetail.approvalRequestDto.remark }}</span>
      </el-form-item>

      <el-form-item v-if="approvalDetail.approvalRequestDto.imageUrls != null" label="图片：">
        <el-image style="width: 100px; height: 100px; margin-left: 5px;" v-for="item in approvalDetail.imagesDto"
          :key="item.url" :src="item.url" :preview-src-list="item.srcList" fit="cover" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="approvalDetailDialogVisible = false">
          关闭
        </el-button>
      </div>
    </template>
  </el-dialog> -->

  <!-- 查看详情弹窗 -->
  <el-dialog v-model="approvalDetailDialogVisible" title="详情信息" width="60%" align-center>
    <div style="max-height: 70vh; overflow-y: auto;">
      <div v-if="null != detailForm" style="margin: 10px; padding: 10px;">
        <el-descriptions title="申请信息" :column="2" border>
          <!-- templateType=2 船员证书模板 -->
          <template v-if="detailForm.templateType == '2'">
            <el-descriptions-item label="证书类型">
              {{ formatTemplateType(detailForm.templateType) }}
            </el-descriptions-item>
            <el-descriptions-item label="姓名">
              <span v-if="!isEditing">{{ detailForm.realName }}</span>
              <el-input v-else v-model="editForm.realName" placeholder="请输入姓名" size="small"></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="国籍">
              {{ detailForm.nationality }}
            </el-descriptions-item>
            <el-descriptions-item :label="detailForm.nationality == '中国' ? '身份证' : '护照'">
              {{ detailForm.idCard }}
            </el-descriptions-item>
            <el-descriptions-item label="电话">
              {{ detailForm.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ detailForm.email }}
            </el-descriptions-item>
            <el-descriptions-item label="公司名称" :span="2">
              <span v-if="!isEditing">{{ detailForm.companyName }}</span>
              <el-input v-else v-model="editForm.companyName" placeholder="请输入公司名称" size="small"></el-input>
            </el-descriptions-item>
          </template>

          <!-- 其他templateType模板 -->
          <template v-else>
            <el-descriptions-item label="证书类型">
              {{ formatTemplateType(detailForm.templateType) }}
            </el-descriptions-item>
            <el-descriptions-item label="国籍">
              {{ detailForm.nationality }}
            </el-descriptions-item>
            <el-descriptions-item label="姓名">
              <span v-if="!isEditing">{{ detailForm.realName }}</span>
              <el-input v-else v-model="editForm.realName" placeholder="请输入姓名" size="small"></el-input>
            </el-descriptions-item>
            <el-descriptions-item :label="detailForm.nationality == '中国' ? '身份证' : '护照'">
              {{ detailForm.idCard }}
            </el-descriptions-item>
            <el-descriptions-item label="电话">
              {{ detailForm.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ detailForm.email }}
            </el-descriptions-item>
            <!-- 特殊字段：培训时间和证件照 -->
            <el-descriptions-item v-if="detailForm.templateType == '0'" label="培训时间">
              {{ dateFormatterMonth(detailForm.trainTime) }}
            </el-descriptions-item>
            <el-descriptions-item v-if="detailForm.templateType == '0'" label="证件照">
              <el-image style="width: 100px; height: 100px" :src="detailForm.idPhoto"
                :preview-src-list="detailForm.srcList">
              </el-image>
            </el-descriptions-item>
            <el-descriptions-item label="公司名称">
              <span v-if="!isEditing">{{ detailForm.companyName }}</span>
              <el-input v-else v-model="editForm.companyName" placeholder="请输入公司名称" size="small"></el-input>
            </el-descriptions-item>
            <el-descriptions-item label="公司地址">
              {{ detailForm.companyAddress }}
            </el-descriptions-item>
            <el-descriptions-item label="公司官网">
              {{ detailForm.companyOfficialWebsite }}
            </el-descriptions-item>
            <el-descriptions-item label="公司联系人">
              {{ detailForm.companyManager }}
            </el-descriptions-item>
            <el-descriptions-item label="公司联系人电话">
              {{ detailForm.companyManagerPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="公司联系人邮箱">
              {{ detailForm.companyManagerEmail }}
            </el-descriptions-item>
          </template>
        </el-descriptions>
      </div>
      
      <!-- 审批信息 -->
      <el-descriptions title="审批信息" :column="2" border style="margin-top: 20px;">
        <el-descriptions-item label="申请人">
          {{ approvalDetail.approvalRequestDto.applicantName }}
        </el-descriptions-item>
        <el-descriptions-item label="模板名称">
          {{ approvalDetail.approvalTemplateDto.templateName }}
        </el-descriptions-item>
        <el-descriptions-item v-if="null != detailForm && null != detailForm.certName" label="证书名称">
          {{ detailForm.certName }}
        </el-descriptions-item>
        <el-descriptions-item v-else label="申请描述">
          {{ approvalDetail.approvalRequestDto.description }}
        </el-descriptions-item>
        <el-descriptions-item label="审批状态" :span="2">
          <el-tag :type="getStatusTagType(approvalDetail.approvalRequestDto.status)">
            {{ formatRequestStatus(approvalDetail.approvalRequestDto.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 审批流程 -->
      <div style="margin-top: 20px;">
        <div style="font-size: 16px; font-weight: bold; margin-bottom: 15px; color: #409EFF; text-align: center;">
          审批流程
        </div>
        <el-steps :align-center="true" direction="horizontal">
          <el-tooltip class="item" effect="dark" placement="top-start" v-for="(item, key) in steps" :key="key"
            :content="item.tooltipInfo">
            <el-step :title="item.title" :status="item.status">
              <template #description>
                <!-- 或签 -->
                <div v-if="item.approvalType == 1">
                  <span>{{ item.description }}</span>
                </div>
                <!-- 会签 -->
                <template v-if="item.approvalType == 2">
                  <div v-for="(desc, index) in item.description" :key="desc.key || index"
                    style="font-size: 13px;">
                    <span>{{ desc.name }}</span><span>({{ desc.result }})</span><br><span>{{ desc.time }}</span>
                  </div>
                </template>
              </template>
            </el-step>
          </el-tooltip>
        </el-steps>
      </div>

      <!-- 其他信息 -->
      <el-descriptions v-if="approvalDetail.approvalRequestDto.remark || approvalDetail.approvalRequestDto.imageUrls" 
        title="其他信息" :column="1" border style="margin-top: 20px;">
        <el-descriptions-item v-if="approvalDetail.approvalRequestDto.remark" label="拒绝原因">
          <span style="color: #F56C6C;">{{ approvalDetail.approvalRequestDto.remark }}</span>
        </el-descriptions-item>
        <el-descriptions-item v-if="approvalDetail.approvalRequestDto.imageUrls != null" label="相关图片">
          <el-image style="width: 100px; height: 100px; margin-right: 10px;" v-for="item in approvalDetail.imagesDto"
            :key="item.url" :src="item.url" :preview-src-list="item.srcList" fit="cover" />
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="approvalDetailDialogVisible = false">关闭</el-button>
        <el-button v-if="!isEditing" type="primary" @click="startEdit">编辑</el-button>
        <el-button v-if="isEditing" type="success" @click="submitEdit" :loading="submitEditLoading">提交</el-button>
        <el-button v-if="isEditing" @click="cancelEdit">取消</el-button>
        <el-button v-if="approvalDetail.approvalTemplateDto && approvalDetail.approvalTemplateDto.approvalType == 1 && detailForm && detailForm.templateType != '2'" 
          type="warning" @click="handleInfoShowFromDetail">信息录入</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 信息录入弹窗 -->
  <SystemDialog title="信息录入" :visible="dialogTableVisible_audit" :height="30" :width="30"
    @on-close="dialogTableVisible_audit = false" @on-confirm="submitApplyCert">
    <template v-slot:content>
      <div style="padding: 20px;">
        <el-form label-width="120px" :inline="false">
          <el-form-item label="培训地点：">
            <el-input placeholder="培训地点" v-model="auditForm.trainAddress"></el-input>
          </el-form-item>
          <!-- <el-form-item label="所属区域：">
            <el-input placeholder="所属区域" v-model="auditForm.certArea"></el-input>
          </el-form-item> -->

          <el-form-item label="技能1：" v-if="auditForm.templateType == 1">
            <el-input placeholder="技能1" v-model="auditForm.auditTechnical1"></el-input>
          </el-form-item>

          <el-form-item label="技能2：" v-if="auditForm.templateType == 1">
            <el-input placeholder="技能2" v-model="auditForm.auditTechnical2"></el-input>
          </el-form-item>

          <el-form-item label="证书类型：" v-if="auditForm.templateType == 1">
            <el-input placeholder="证书类型" v-model="auditForm.auditModels"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </SystemDialog>

  <!-- 审批结果弹窗 -->
  <el-dialog v-model="approvalDialogVisible" title="审批" width="30%" align-center>
    <el-form :model="record" ref="recordRef" :rules="recordRules" label-width="80px" :inline="false">
      <el-form-item label="审批结果" prop="approveResult">
        <el-select v-model="record.approveResult" filterable placeholder="请选择审批结果">
          <el-option label="同意" value=1></el-option>
          <el-option label="拒绝" value=2></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批意见" prop="comments">
        <el-input type="textarea" :rows="4" v-model="record.comments" placeholder="审批意见"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="approvalDialogVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="submitRecord" :loading="submitRecordLoading">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 浏览pdf文件 -->
  <PDFViewer ref="pdfViewerRef"></PDFViewer>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue"
import { dateFormatter, dateFormatterDay, dateFormatterMonth } from '~/utils/common.js'
import { toast, toastWarn } from "~/composables/util"
import SystemDialog from "~/components/SystemDialog.vue";
import PDFViewer from '~/components/pdfView.vue';
import { checkContainsChinese1 } from '~/utils/validate.js'
import { formatRequestStatus, getApprovalTemplateList, formatRecordResult, getRecordTodo, approve, getRequestInfoById } from "~/api/approvalApi"
import { api_cert_apply_id, api_cert_apply_enterInfo, api_cert_apply_certPreview,api_cert_apply_updatePersonalInfo } from "~/api/exam/certApi"

// 审批弹窗
const approvalDialogVisible = ref(false)
// 审批结果表单
const recordRef = ref(null)
// 审批结果
const record = reactive({
  recordId: null,
  approveResult: null,
  comments: null,
})
// 审批结果表单校验
const recordRules = {
  approveResult: [
    { required: true, message: '审批结果不能为空', trigger: 'change' }
  ],
  comments: [
    { required: true, message: '审批意见不能为空', trigger: 'change' }
  ]
}

// 提交审批按钮loading
const submitRecordLoading = ref(false)

// 审批详情弹窗
const approvalDetailDialogVisible = ref(false)
// 审批详情
const approvalDetail = reactive({
  approvalTemplateDto: null,
  approvalRequestDto: null,
  imagesDto: null
})
// steps
const steps = ref([])

// 证书申请详情form
const detailForm = ref(null)

// 编辑相关状态
const isEditing = ref(false)
const submitEditLoading = ref(false)
// 编辑表单数据
const editForm = reactive({
  realName: '',
  companyName: ''
})

// 信息录入
const dialogTableVisible_audit = ref(false)

// 信息录入表单
const auditForm = reactive({
  id: null,
  templateType: null,
  trainAddress: null,
  // certArea: null,
  auditTechnical1: null,
  auditTechnical2: null,
  auditModels: null,
})

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

// 查询条件
const searchForm = reactive({
  templateId: null,
  page: currentPage.value,
  size: limit.value,
})

// 重置搜索框
const resetSearchForm = () => {
  searchForm.templateId = null
  initTableData(1)
}

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 模板字典数据
const templateDic = ref([])

// 生命周期函数
onMounted(() => {
  //初始化模板字典数据
  initTemplateDic()
  //初始化列表数据
  initTableData()
})

// 获取模板字典数据
function initTemplateDic() {
  getApprovalTemplateList()
    .then(res => {
      if (res) {
        templateDic.value = res.filter(template => template.state == 1)
      }
    })
}

// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  getRecordTodo(searchForm)
    .then(res => {
      if (res && res.records) {
        tableData.value = res.records
        total.value = res.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 查看详情
const handleShow = async (row) => {
  // 清除编辑状态
  isEditing.value = false
  editForm.realName = ''
  editForm.companyName = ''
  await getRequestInfoById(row.requestId)
    .then(res => {
      approvalDetail.approvalTemplateDto = res.approvalTemplateDto
      approvalDetail.approvalRequestDto = res.approvalRequestDto
      let imageUrls = res.approvalRequestDto.imageUrls
      if (null != imageUrls && imageUrls.length > 0) {
        let result = []
        let imgs = imageUrls.split(",")
        let item = null
        for (let i = 0; i < imgs.length; i++) {
          item = {}
          item.url = imgs[i]
          item.srcList = [imgs[i]]
          result.push(item)
        }
        approvalDetail.imagesDto = result
      }

      //构建流程节点图
      let nodeList = res.approvalTemplateDto.nodeDtoList
      steps.value = []
      let defaultStep = { approvalType: 1, title: "提交申请", status: "success", tooltipInfo: "流程起点", description: dateFormatter(res.approvalRequestDto.createTime) }
      steps.value.push(defaultStep)
      let step = null
      //会签描述信息
      let descList = []
      //审核人list
      let nameList = []
      //审核结果list
      let resultList = []
      //审核时间list
      let resultDateList = []
      //审核备注信息
      let commentsList = []

      for (let i = 0; i < nodeList.length; i++) {

        //重置数据---------
        step = {}
        descList = []
        nameList = []
        resultList = []
        resultDateList = []
        commentsList = []
        //重置数据---------

        //当前节点审批方式
        let approvalType = nodeList[i].approvalType
        //获取审批人list
        let approvalRecordList = nodeList[i].approvalRecordDtos
        for (let j = 0; j < approvalRecordList.length; j++) {
          nameList.push(approvalRecordList[j].approverName)
          resultList.push(approvalRecordList[j].approvalResult)
          resultDateList.push(dateFormatter(approvalRecordList[j].approvalTime))
          commentsList.push(approvalRecordList[j].comments)
          //会签特殊处理描述字段
          if (approvalType == 2) {
            let desc = {}
            desc.key = j
            desc.name = nameList[j]
            desc.result = formatRecordResult(resultList[j])
            desc.time = resultDateList[j]
            descList.push(desc)
          }
        }

        //提示信息
        step.tooltipInfo = "处理人: " + nameList.join("; ")

        //审批类型，1：或签，2：会签
        if (nodeList[i].approvalType == 1) {
          //审批类型
          step.approvalType = 1

          //审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
          if (resultList.indexOf(0) !== -1) {
            //标题
            step.title = "未处理"
            //节点描述
            step.description = null
            //节点状态
            step.status = "wait"
            steps.value.push(step)
          } else if (resultList.indexOf(3) !== -1) {
            //标题
            step.title = "处理中"
            //节点描述
            step.description = null
            //节点状态
            step.status = "process"
            steps.value.push(step)
          } else if (resultList.indexOf(1) !== -1) {
            let successIndex = resultList.indexOf(1)
            //标题（此处是审核人）
            step.title = nameList[successIndex]
            //节点描述（此处是审核时间）
            step.description = resultDateList[successIndex]
            //节点状态；审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
            step.status = "success"
            steps.value.push(step)
          } else if (resultList.indexOf(2) !== -1) {
            let errorIndex = resultList.indexOf(2)
            //标题（此处是审核人）
            step.title = nameList[errorIndex]
            //节点描述（此处是审核时间）
            step.description = resultDateList[errorIndex]
            //节点状态；审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
            step.status = "error"
            //如果是拒绝显示原因
            approvalDetail.approvalRequestDto.remark = commentsList[errorIndex]

            steps.value.push(step)
          }
        }

        else if (nodeList[i].approvalType == 2) {
          //审批类型
          step.approvalType = 2

          //审批结果，0未处理，1：同意，2：拒绝，3：处理中，4：他人已处理
          if (resultList.indexOf(0) !== -1) {
            //标题
            step.title = "未处理"
            //节点描述
            step.description = null
            //节点状态
            step.status = "wait"
            steps.value.push(step)
          } else {
            //标题
            step.title = null
            //节点状态
            if (resultList.indexOf(2) !== -1) {
              step.status = "error"
              //如果是拒绝显示原因
              approvalDetail.approvalRequestDto.remark = commentsList[resultList.indexOf(2)]

            } else if (resultList.indexOf(3) !== -1) {
              step.status = "process"
            } else {
              step.status = "success"
            }
            step.description = descList
            steps.value.push(step)
          }
        }
      }

      //申请人名称
      approvalDetail.approvalRequestDto.applicantName = row.applicantName

      //approvalDetailDialogVisible.value = true
    })

  //获取申请信息
  if (null != row.approvalType && row.approvalType == 1) {
    await api_cert_apply_id(approvalDetail.approvalRequestDto.description).then(res => {
      detailForm.value = res
      detailForm.value.srcList = [res.idPhoto]
    })
  } else {
    detailForm.value = null
  }

  //打开弹窗
  approvalDetailDialogVisible.value = true
}

// 信息录入
const handleInfoShowFromDetail = () => {
  if (approvalDetail.approvalRequestDto && approvalDetail.approvalRequestDto.description) {
    api_cert_apply_id(approvalDetail.approvalRequestDto.description).then(res => {
      auditForm.id = res.id
      //证书模板 0工程师证书 1公司证书 2船员证书
      auditForm.templateType = res.templateType
      auditForm.trainAddress = res.trainAddress
      // auditForm.certArea = res.certArea
      auditForm.auditTechnical1 = res.auditTechnical1
      auditForm.auditTechnical2 = res.auditTechnical2
      auditForm.auditModels = res.auditModels
      console.log(JSON.stringify(auditForm))
      dialogTableVisible_audit.value = true
    })
  }
}

//证书预览
const pdfViewerRef = ref(null)
const certPreview = (row) => {

  //证书申请审批
  if (null != row.approvalType && row.approvalType == 1) {

    //table loading
    loading.value = true

    getRequestInfoById(row.requestId).then(res => {
      api_cert_apply_id(res.approvalRequestDto.description).then(res => {

        if (null == res) {
          toastWarn("信息不存在")
          loading.value = false
          return
        }

        if (res.templateType == 0) {
          if (null == res.trainAddress || "" == res.trainAddress || null == res.trainAddress || "" == res.trainAddress) {
            toastWarn("请先信息录入")
            loading.value = false
            return
          }
        } else if (res.templateType == 1) {
          if (null == res.auditTechnical1 || "" == res.auditTechnical1 || null == res.auditTechnical2 || "" == res.auditTechnical2 || null == res.auditModels || "" == res.auditModels) {
            toastWarn("请先信息录入")
            loading.value = false
            return
          }
        }

        //预览证书pdf
        if (res.certUrl) {
          loading.value = false
          pdfViewerRef.value.showDocVisible(res.certUrl)
        } else {
          api_cert_apply_certPreview(res.id).then(res => {
            setTimeout(() => {
              pdfViewerRef.value.showDocVisible(res)
            }, 2000);
          }).finally(() => {
            loading.value = false
          })
        }
      })
    })
  }
}

// 提交审核
function submitApplyCert() {

  //培训地点、所属区域，不能为空
  if (null == auditForm.trainAddress || "" == auditForm.trainAddress) {
    toastWarn("培训地点不能为空")
    return
  }
  //培训地点、所属区域，不能为空，不能为中文
  if (checkContainsChinese1(auditForm.trainAddress)) {
    toastWarn("培训地点不能有中文")
    return
  }

  // if (null == auditForm.certArea || "" == auditForm.certArea) {
  //   toastWarn("所属区域不能为空")
  //   return
  // }

  //如果是公司证书，则以下不能为空
  if (auditForm.templateType == 1) {
    if (null == auditForm.auditTechnical1 || "" == auditForm.auditTechnical1) {
      toastWarn("技能1不能为空")
      return
    }
    if (checkContainsChinese1(auditForm.auditTechnical1)) {
      toastWarn("技能1不能有中文")
      return
    }
    if (null == auditForm.auditTechnical2 || "" == auditForm.auditTechnical2) {
      toastWarn("技能2不能为空")
      return
    }
    if (checkContainsChinese1(auditForm.auditTechnical2)) {
      toastWarn("技能2不能有中文")
      return
    }
    if (null == auditForm.auditModels || "" == auditForm.auditModels) {
      toastWarn("证书类型不能为空")
      return
    }
    if (checkContainsChinese1(auditForm.auditModels)) {
      toastWarn("证书类型不能有中文")
      return
    }
  }

  api_cert_apply_enterInfo(auditForm).then(res => {
    dialogTableVisible_audit.value = false
    toast("录入成功")
  })
}

// 打开审批弹窗
const showApprovalDialog = (row) => {

  //证书申请审批
  if (null != row.approvalType && row.approvalType == 1) {
    getRequestInfoById(row.requestId).then(res => {
      api_cert_apply_id(res.approvalRequestDto.description).then(res => {
        if (res.templateType == 0) {
          if (null == res.trainAddress || "" == res.trainAddress || null == res.trainAddress || "" == res.trainAddress) {
            toastWarn("请先信息录入")
            return
          }
        } else if (res.templateType == 1) {
          if (null == res.auditTechnical1 || "" == res.auditTechnical1 || null == res.auditTechnical2 || "" == res.auditTechnical2 || null == res.auditModels || "" == res.auditModels) {
            toastWarn("请先信息录入")
            return
          }
        }

        if (null == res.certUrl || "" == res.certUrl) {
          toastWarn("请先生成预览")
          return
        }

        //重置表单
        resetRecordForm()
        //设置record id
        record.recordId = row.recordId
        approvalDialogVisible.value = true
      })
    })
  } else {
    //重置表单
    resetRecordForm()
    //设置record id
    record.recordId = row.recordId
    approvalDialogVisible.value = true
  }
}

// 重置record表单
const resetRecordForm = () => {
  record.recordId = null
  record.comments = null
  record.approveResult = null
  if (recordRef.value) recordRef.value.resetFields()
}

// 提交审批结果表单
const submitRecord = () => {
  //console.log("form:",JSON.stringify(record))
  //表单校验
  recordRef.value.validate((valid) => {
    if (!valid) return
    submitRecordLoading.value = true
    //审批
    approve(record)
      .then(res => {
        toast("审批成功")
        // 刷新界面
        initTableData(null)
      }).finally(() => {
        approvalDialogVisible.value = false
        submitRecordLoading.value = false
      })

  }).finally(() => {
  })
}

const formatTemplateType = (type) => {
  if (type == '0') {
    return "工程师证书"
  } else if (type == '1') {
    return "公司证书"
  } else if (type == '2') {
    return "船员证书"
  } else {
    return "未知"
  }
}

// 开始编辑
const startEdit = () => {
  if (detailForm.value) {
    editForm.realName = detailForm.value.realName || ''
    editForm.companyName = detailForm.value.companyName || ''
    isEditing.value = true
  }
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  editForm.realName = ''
  editForm.companyName = ''
}

// 提交编辑
const submitEdit = () => {
  if (!editForm.realName || !editForm.companyName) {
    toastWarn('姓名和公司名称不能为空')
    return
  }
  
  submitEditLoading.value = true
  
  // 构建更新数据
  const updateData = {
    id: detailForm.value.id,
    realName: editForm.realName,
    companyName: editForm.companyName
  }
  
  // 调用后端API提交修改
  api_cert_apply_updatePersonalInfo(updateData).then(res => {
    // 更新本地数据
    if (detailForm.value) {
      detailForm.value.realName = editForm.realName
      detailForm.value.companyName = editForm.companyName
    }
    toast('修改成功')
    isEditing.value = false
  }).catch(err => {
    toastWarn('修改失败')
    console.error('修改失败:', err)
  }).finally(() => {
    submitEditLoading.value = false
  })
}

// 获取审批状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 0:
      return 'warning' // 待审批
    case 1:
      return 'success' // 审批通过
    case 2:
      return 'danger'  // 审批拒绝
    case 3:
      return 'info'    // 审批中
    case 4:
      return 'info'    // 取消申请
    default:
      return 'info'
  }
}
</script>

<style lang="scss">
.el-step__head.is-process {
  border-color: darkorange;
  color: darkorange
}

.el-step__title.is-process {
  color: darkorange
}
</style>